package com.wrq.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;

import java.io.*;
import java.util.List;

/**
 *  接受List集合，把list上传到自定义的ftp服务器上面去
 */
@Slf4j
public class FTPUtil {

    private  static  String ftpServerIp = "59.110.155.222";
    private  static  String ftpUser = "hushuyan";
    private  static  String ftpPass = "pwNG3BjeLCFNsCia";
    static String  endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
    static String accessKeyId = "LTAI5tCEdjwXf6epbiBa33FS";
    static String accessKeySecret = "GKjeCRhJyeySitB6XSE4SNZSVtMn1i";
    static String bucketName = "edu-course-file";

    public static void OOSUpload(String fileName, FileInputStream fileInputStream) throws FileNotFoundException {
        // Endpoint以杭州为例，其它Region请按实际情况填写。


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        PutObjectResult result = ossClient.putObject(bucketName, fileName, fileInputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        log.info("上传成功");
    }
    public static void OOSUpload(String fileName, File file) throws FileNotFoundException {
        // Endpoint以杭州为例，其它Region请按实际情况填写。


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。
        PutObjectResult result = ossClient.putObject(bucketName, fileName, file);

        // 关闭OSSClient。
        ossClient.shutdown();
        log.info("上传成功");
    }

    public static void main(String[] args) {


    }

    public  static InputStream OOSDownLoad(String objectName ) {
        InputStream inputStream = null;
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            inputStream = ossObject.getObjectContent();

            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return inputStream;
    }



    //对面开放的upload方法
    public static InputStream uploadFile(String uploadFileName, File file ,String path) throws IOException {
        FTPUtil ftpUtil = new FTPUtil();
        log.info("开始连接ftp服务器");
        FileInputStream result = ftpUtil.uploadFile1(  uploadFileName, file,path);
        log.info("开始连接ftp服务器，结束上传，上传结果:{}",result);
        return result;
    }

    //对面开放的upload方法
    public static boolean downloadFile(String remotePath, String newFileName, String targetFilePath) throws IOException {
        FTPUtil ftpUtil = new FTPUtil();

        boolean result = ftpUtil.download(remotePath, newFileName, targetFilePath);
        return result;
    }

    private  FileInputStream uploadFile1(String uploadFileName,File file,String path  ) throws IOException {
        boolean uploaded = true;
        FileInputStream fis = null;

                fis  = new FileInputStream(file);
//                    ftpClient.storeFile(fileItem.getName(),fis);
                OOSUpload(path+uploadFileName,fis);



        return  fis;
    }

    private boolean  download(String remotePath, String newFileName, String targetFilePath) throws IOException {
        boolean download = true;
        FileOutputStream fos = null;

        if(connectServer(this.ip,this.port,this.user,this.pwd)){
            try {

            ftpClient.changeWorkingDirectory(remotePath);
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();

            //设置要下载到的目录： "/upload/54848484.doc"
            File localFile = new File(targetFilePath);
            //得到输出
            fos = new FileOutputStream(localFile);
            ftpClient.retrieveFile(newFileName, fos); //开始下载文件

            } catch (IOException e) {
                log.error("从ftp服务器下载文件异常",e);
                download  = false;
                e.printStackTrace();
            }finally {
                fos.close();
                ftpClient.disconnect();
            }
        }
        return  download;
    }

    //连接ftp
    private boolean connectServer(String ip,int port,String user,String pwd){
        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user,pwd);
            log.info("ftp连接成功");
        } catch (IOException e){
            log.error("连接FTP服务器异常",e);
            e.printStackTrace();
        }
        return  isSuccess;
    }

    private  String ip;
    private  int port;
    private  String user;
    private  String pwd;
    private FTPClient ftpClient;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
}
